package com.tanguy.user.ui.map.activity

import android.app.Activity
import android.content.Intent
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
import android.text.TextUtils
import android.view.View
import com.amap.api.maps.AMap
import com.amap.api.maps.AMapOptions
import com.amap.api.maps.CameraUpdateFactory
import com.amap.api.maps.model.CameraPosition
import com.amap.api.maps.model.LatLng

import com.amap.api.services.core.LatLonPoint
import com.amap.api.services.geocoder.*
import com.tanguy.user.Const
import com.tanguy.user.R
import com.tanguy.user.bean.PlaceShowBean
import com.tanguy.user.bean.station.CityBean
import com.tanguy.user.ui.map.adapter.PlaceShowAdapter
import com.tanguy.user.ui.trip.activity.choice.ChoiceCityActivity
import com.tanguy.user.utlis.extend.click
import com.tanguy.user.utlis.extend.getTitleText
import com.tanguy.user.utlis.extend.location
import com.tanguy.user.utlis.extend.visibility
import org.jetbrains.anko.find
import org.jetbrains.anko.startActivityForResult


/**
 * Created by dab on 2017/11/15 0015 15:58
 * 在地图找点
 * 需要传cityCode,cityName,type(默认为0)
 * type 1:注册酒店选取地址的(不能切换城市和定位)
 * type 2:接送站机使用的(可以切换城市)
 */
class MapFindCoordinateActivity : BaseMapActivity() {
    override fun setContentViewRes(): Int = R.layout.activity_map_find_coordinate
    private var type = 0
    private val geocodeSearch by lazy { GeocodeSearch(this) }
    private val content by lazy { find<RecyclerView>(R.id.rv_content) }
    private val placeShowAdapter by lazy { PlaceShowAdapter(mPlaceShowList) }
    private val mPlaceShowList by lazy { ArrayList<PlaceShowBean>() }
    var placeShowBean: PlaceShowBean?=null

//    var streetNumber: StreetNumber? = null
    var showName: String? = null
    var thisCityCode: String? = null
    lateinit var cityCode: String
    lateinit var cityName: String
    override fun initView() {
        super.initView()
        cityCode = intent.getStringExtra("cityCode")
        cityName = intent.getStringExtra("cityName")
        type = intent.getIntExtra("type", 0)
        title = cityName
        content.layoutManager = LinearLayoutManager(this)
        content.adapter = placeShowAdapter
        titleBar.addRightButton("确定", 0, View.OnClickListener {
            if (placeShowBean == null||placeShowBean!!.name.isEmpty()) {
                showToast("请选择详细地址")
                return@OnClickListener
            }
            if (type == 1 && thisCityCode != cityCode) {
                showToast("选择的地方不在${cityName}内")
                return@OnClickListener
            }
            setResult(Activity.RESULT_OK
                    , Intent().putExtra("name", placeShowBean!!.name)
                    .putExtra("address", placeShowBean!!.address)
                    .putExtra("latitude", placeShowBean!!.latitude.toString())
                    .putExtra("longitude", placeShowBean!!.longitude.toString())
                    .putExtra("cityCode",thisCityCode)
            )
            finish()
        })
        initMapView(cityCode, cityName, type)
    }

    override fun initEvent() {
        super.initEvent()
        click(R.id.tv_search) {
            startActivityForResult<SearchLocationActivity>(Const.RequestCode.SEARCH_LOCATION
                    , "cityCode" to cityCode
                    , "cityName" to cityName
            )
        }
        click(R.id.tv_location) {
            location {
                if (it != null) {
                    moveCamera(it.latitude, it.longitude, 18f)
                }
            }
        }
        aMap.setOnCameraChangeListener(object : AMap.OnCameraChangeListener {
            override fun onCameraChangeFinish(p0: CameraPosition?) {
                if (p0 == null) return
                getAddressByLatlng(p0.target)
//                poiSearch(p0)
            }

            override fun onCameraChange(p0: CameraPosition?) {}
        })
        placeShowAdapter.setOnItemClick {
            _, _, data ->
            animateCamera(data.latitude.toDouble(), data.longitude.toDouble(), 18f)
        }
    }


    /**
     * 初始化地图
     */
    private fun initMapView(cityCode: String, cityName: String, type: Int) {
        // 通用设置
        val uiSettings = aMap.uiSettings
        uiSettings.isZoomControlsEnabled = false
        uiSettings.logoPosition = AMapOptions.LOGO_POSITION_BOTTOM_RIGHT//设置logo位置
        geocodeSearch.setOnGeocodeSearchListener(mGeocodeSearch)
        if (type == 1) {
            visibility(R.id.tv_location,false)
            val query = GeocodeQuery(cityName, cityName)
            geocodeSearch.getFromLocationNameAsyn(query)
        } else if (type == 2) {
            title = getTitleText(intent.getStringExtra("cityName"))
            val lon = intent.getDoubleExtra("lon", 0.0)
            val lat = intent.getDoubleExtra("lat", 0.0)
            moveCamera(lat, lon, 16f)
            click(titleBar.titleView) {
                startActivityForResult<ChoiceCityActivity>(Const.RequestCode.SERVICE_CITY, Const.IntentCode.CITY_NAME to cityName)
            }
        }
    }

    private fun getAddressByLatlng(latLng: LatLng) {
        //逆地理编码查询条件：逆地理编码查询的地理坐标点、查询范围、坐标类型。
        val latLonPoint = LatLonPoint(latLng.latitude, latLng.longitude)
        val query = RegeocodeQuery(latLonPoint, 500f, GeocodeSearch.AMAP)
        //异步查询
        geocodeSearch.getFromLocationAsyn(query)
    }


    /**
     * 搜索结果
     */
    private val mGeocodeSearch = object : GeocodeSearch.OnGeocodeSearchListener {
        override fun onRegeocodeSearched(regeocodeResult: RegeocodeResult, i: Int) {
            if (i == 1000) {
                placeShowBean = PlaceShowBean()
                placeShowBean!!.latitude=regeocodeResult.regeocodeQuery.point.latitude.toString()
                placeShowBean!!.longitude=regeocodeResult.regeocodeQuery.point.longitude.toString()
                val streetNumber = regeocodeResult.regeocodeAddress.streetNumber
                placeShowBean!!.address= streetNumber.street+streetNumber.number

                val formatAddress = regeocodeResult.regeocodeAddress.formatAddress
                val replace = formatAddress.replace(regeocodeResult.regeocodeAddress.province, "")
                        .replace(regeocodeResult.regeocodeAddress.city, "")
                        .replace(regeocodeResult.regeocodeAddress.district, "")
                        .replace(regeocodeResult.regeocodeAddress.township, "")
                placeShowBean!!.name=replace

                val adCode = regeocodeResult.regeocodeAddress.adCode
                thisCityCode= adCode.substring(0,adCode.length-2)+"00"
                val aois = regeocodeResult.regeocodeAddress.aois
                if (aois.size > 0) {
                    showName=aois[0].aoiName
                }
                val pois = regeocodeResult.regeocodeAddress.pois
                mPlaceShowList.clear()
                (0 until pois.size).mapTo(mPlaceShowList) {
                    val poiItem = pois[it]
//                    poiItem.title, poiItem.snippet, poiItem.latLonPoint.latitude, poiItem.latLonPoint.longitude

                    PlaceShowBean().init(poiItem.title,poiItem.snippet,poiItem.latLonPoint.latitude,poiItem.latLonPoint.longitude)
                }
                if (TextUtils.isEmpty(showName)&&mPlaceShowList.size>0) {
                    showName=mPlaceShowList[0].name
                }
                placeShowAdapter.notifyDataSetChanged()
            }

        }

        override fun onGeocodeSearched(geocodeResult: GeocodeResult, i: Int) {
            if (i == 1000) {
                if (geocodeResult.geocodeAddressList.size >= 1) {
                    val geocodeAddress = geocodeResult.geocodeAddressList[0]
                    val latLonPoint = geocodeAddress.latLonPoint
                    moveCamera(latLonPoint.latitude, latLonPoint.longitude, 18f)
                }
            }
        }
    }

    /**
     * 移动地图
     */
    private fun moveCamera(latitude: Double, longitude: Double, zoom: Float) {
        aMap.moveCamera(CameraUpdateFactory.newLatLngZoom(LatLng(latitude, longitude), zoom))
    }

    private var mapMoving = false
    /**
     * 移动地图
     */
    private fun animateCamera(latitude: Double, longitude: Double, zoom: Float) {
        mapMoving = true
        aMap.animateCamera(CameraUpdateFactory.newLatLngZoom(LatLng(latitude, longitude), zoom), object : AMap.CancelableCallback {
            override fun onFinish() {
                mapMoving = false
            }

            override fun onCancel() {
                mapMoving = false
            }

        })
    }


    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode == Activity.RESULT_OK) {
            if (requestCode == Const.RequestCode.SEARCH_LOCATION && data != null) {
                val latitude = data.getDoubleExtra(Const.IntentCode.LATITUDE, 0.0)
                val longitude = data.getDoubleExtra(Const.IntentCode.LONGITUDE, 0.0)
                animateCamera(latitude, longitude, 20f)
            }
            if (requestCode == Const.RequestCode.SERVICE_CITY && data != null) {
                val cityBean = data.getParcelableExtra<CityBean>(Const.IntentCode.CITY_BEAN)
                cityCode = cityBean.cityCode
                cityName = cityBean.name
                title = getTitleText(cityBean.name)
                val query = GeocodeQuery(cityBean.name, cityBean.name)
                geocodeSearch.getFromLocationNameAsyn(query)

            }
        }

    }
}